package org.pt.utils;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import static org.pt.config.Constants.VECODE_EXPIRE_SECOND;

@Component
public final class EmailCodeUtils {

    private static StringRedisTemplate staticRedisTemplate;
    private static final int CODE_LENGTH = 6; // 验证码位数

    @Autowired
    private StringRedisTemplate redisTemplate; // Spring注入

    // 初始化静态RedisTemplate
    @PostConstruct
    private void init() {
        staticRedisTemplate = this.redisTemplate;
    }

    // 禁止实例化
    private EmailCodeUtils() {}

    /**
     * 生成6位数字验证码
     */
    public static String generateCode() {
        return String.valueOf(new Random().nextInt(899999) + 100000);
    }

    /**
     * 保存验证码到Redis（默认5分钟过期）
     * @param email 邮箱地址
     * @param code  验证码
     */
    public static void saveCode(String email, String code) {
        staticRedisTemplate.opsForValue().set(buildRedisKey(email), code, VECODE_EXPIRE_SECOND, TimeUnit.SECONDS);
    }

    /**
     * 验证邮箱验证码
     * @param email 邮箱地址
     * @param code  用户输入的验证码
     * @return true=验证成功，false=验证失败
     */
    public static boolean verifyCode(String email, String code) {
        String storedCode = staticRedisTemplate.opsForValue().get(buildRedisKey(email));
        return code != null && code.equals(storedCode);
    }

    /**
     * 删除验证码（验证成功后调用）
     */
    public static void deleteCode(String email) {
        staticRedisTemplate.delete(buildRedisKey(email));
    }

    // 构建Redis键（避免冲突）
    private static String buildRedisKey(String email) {
        return "email:code:" + email;
    }
}
